<?php

namespace app\common\service\GoodsService;

use app\common\service\OrderService\OrderCheckService;
use app\common\service\OrderService\OrderCloudService;
use app\model\BbcModel\BusinessGoods;
use app\model\BbcModel\Country;
use think\facade\Db;
use app\Normal;
use app\model\BbcLogModel\Sync;
use app\model\BbcLogModel\SyncCount;
use app\model\BbcLogModel\GoodsSyncLog;
use app\model\BbcModel\Goods;
use app\model\BbcModel\GoodsTags;
use app\model\BbcModel\GoodsAttach;
use app\model\BbcModel\GoodsSupplyClass;
use app\model\BbcModel\GoodsSpecPrice;
use app\model\BbcModel\GoodsService;
use app\model\BbcModel\TransitTemplate;
use app\model\BbcModel\ExpressTemplate;
use app\model\BbcModel\Storage;
use app\common\service\SystemRabbitMqService\MessageService\YunCangMessageService;
use app\model\BbcModel\GoodsClass;
use app\model\BbcModel\GoodsBrand;
use app\model\BbcModel\GoodsBatch;
use app\common\service\SystemRabbitMqService\MessageService\GoodsElasticSearchMessageService;

/**
 * 商品同步中心
 * @author linan
 */
class SyncGoodsService
{
    public $successCount=0;
    public $time;
    
    /**
     * 将推送过来的商品放入队列
     * @param array $data
     * @return  array
     */
    public function getGoodsIntoMq( $data = [] )
    {
        $time=time();
        $cid=$data['cid'];
        $MessageId=$post['MessageId']??0;
        $post=$data;
        if(!empty($post['MessageType'])){
            if($post['MessageType']=='OrderExpress'){
                $syncid= Sync::instance()->add([
                    'content'=>rawurldecode(json_encode($post['data'])),
                    'messageType'=>$post['MessageType']??'',
                    'cd'=>$time,
                    'cid'=>$cid,
                    'MessageId'=>$MessageId
                ]);
                if(!is_array($post['data'])){
                    $data['data'] = json_decode(rawurldecode($post['data']),true);
                }else{
                    $data['data']=json_decode(rawurldecode(json_encode($post['data'])),true);
                }
                return (new OrderCheckService())->OrderExpress($data['data']);
            }else{
                $msgdata=['cid'=>$cid,'data'=>$data['data'],'MessageType'=>$post['MessageType'],'logid'=>$MessageId];
                return YunCangMessageService::instance()->produce($msgdata);
            }
        }else{
            return Normal::returnCode(Normal::FAIL,"缺少参数MessageType");
        }
    }
    
    /**
     * 商品变更
     * @param
     * @param array $data
     * @param int $cid
     * @param string $MessageId
     * @return  array
     */
    public function goodsChange( array $message = [] )
    {
        $MessageId   = $message['logid'];
        $cid         = $message['cid'];
        $data        = $message['data'];
        $this->time=time();
        $this->successCount=0;
        $hasMessage=[];
        if($MessageId>0){
            $hasMessage=SyncCount::instance()->info(['MessageId'=>$MessageId]);
            if($hasMessage){
                print_r('已有数量:'.$hasMessage['count']);
            }
        }
        $channelInsert=[];
        $channelDelete=[];
        try {
            foreach ($data as $key=>$value){
                Db::startTrans();
                $goods=$this->goodsCheckout($value,$cid);
                Db::commit();
                if(!empty($goods['channelInsert'])){
                    $channelInsert=array_merge($channelInsert,$goods['channelInsert']);
                }
                if(!empty($goods['channelDelete'])){
                    $channelDelete=array_merge($channelDelete,$goods['channelDelete']);
                }
            }
            
            if(!empty($channelInsert)){
                (new GoodsElasticSearchMessageService('channel'))->pushNew($channelInsert,'insert');
            }
            if(!empty($channelDelete)){
                (new GoodsElasticSearchMessageService('channel'))->pushNew($channelDelete,'delete');
            }
            
            if($MessageId>0){
                print_r('新数量:'.$this->successCount);
                if($hasMessage){
                    $newCount=$this->successCount+$hasMessage['count'];
                    print_r('新数量:'.$newCount);
                    SyncCount::instance()->edit(['id'=>$hasMessage['id']],['count'=>$newCount]);
                    $syncData['message_id']=$MessageId;
                    $syncData['goods_count']=$newCount;
                    $syncData['cid']=$cid;
                    (new OrderCloudService())->sendToStoB($syncData,'SyncUserGoodsCountService');
                }else{
                    $in['cd']=$this->time;
                    $in['MessageId']=$MessageId;
                    $in['count']=$this->successCount;
                    SyncCount::instance()->add($in);
                    $syncData['message_id']=$MessageId;
                    $syncData['goods_count']=$this->successCount;
                    $syncData['cid']=$cid;
                    (new OrderCloudService())->sendToStoB($syncData,'SyncUserGoodsCountService');
                }
            }
            return ['code'=>Normal::SUC,'msg'=>'success'];
        } catch (\Exception $e) {
            Db::rollback();
            $this->successCount=0;
            if($MessageId>0){
                if($hasMessage){
                    $newCount=$hasMessage['count'];
                    SyncCount::instance()->edit(['id'=>$hasMessage['id']],['count'=>$newCount]);
                    $syncData['message_id']=$MessageId;
                    $syncData['goods_count']=$newCount;
                    $syncData['cid']=$cid;
                    (new OrderCloudService())->sendToStoB($syncData,'SyncUserGoodsCountService');
                }else{
                    $in['cd']=$this->time;
                    $in['MessageId']=$MessageId;
                    $in['count']=0;
                    SyncCount::instance()->add($in);
                    $syncData['message_id']=$MessageId;
                    $syncData['goods_count']=0;
                    $syncData['cid']=$cid;
                    (new OrderCloudService())->sendToStoB($syncData,'SyncUserGoodsCountService');
                }
            }
            $msg = $e->getMessage().$e->getLine().$e->getFile();
            return ['code'=>Normal::FAIL,'msg'=>$msg];
        }
    }

    /**
     * 处理商品数据
     * @param array $data
     * @param int $cid
     * @return  array
     */
    public function goodsCheckout($data=[],$cid)
    {
        $return=[];
        $sku = $data['skuList'];
        $goodsInfo=[
            'name'         =>   $data['goodsName'],
            'is_bonded'    =>   $data['goodsType'],
            'wechat_only'  =>   $data['isNeedWeiXinPay']??0,
            'pic_auth'     =>   $data['isNeedUploadIDCard']??0,
            'unit_name'    =>   $data['unitName'],
            'body'         =>   empty($data['description']) ? '' : $data['description'],
            'origin'       =>   empty($data['countryName']) ? '' : $data['countryName']
        ];
        $originInfo=Country::instance()->info(['name'=>$goodsInfo['origin'],'cid'=>$cid]);
        if($originInfo){
            $goodsInfo['origin_id']=$originInfo['id'];
        }else{
            $goodsInfo['origin_id']=Country::instance()->add(['name'=>$goodsInfo['origin'],'cid'=>$cid,'cd'=>time(),'md'=>time()]);
        }
        $tags=$data['tags']??[];
        $tag_ids=[];
        if(!empty($tags) && is_array($tags)){
            foreach ($tags as $v){
                $info=GoodsTags::instance()->info(['cid'=>$cid,'supid'=>$v['id']]);
                if($info){
                    GoodsTags::instance()->edit(['id'=>$info['id']],['name'=>$v['name'],'show_name'=>$v['name']]);
                    $tag_ids[]=$info['id'];
                }else{
                    $tag_ids[]=GoodsTags::instance()->add(['cid'=>$cid,'supid'=>$v['id'],'name'=>$v['name'],'show_name'=>$v['name']]);
                }
            }
        }
        $suptag=empty($tag_ids)?'':implode(',',$tag_ids);
        $goodsInfo['supply_tag']=$suptag;
        $goods_img = empty($data['images']) ? [] : $data['images'];
        $goods_img = is_array($goods_img)?$goods_img:explode(',',$goods_img);
        $goodsInfo['img']=isset($goods_img[0]) ? $goods_img['0'] : '';
        $goods_type = Goods::instance()->is_bonded;
        //查询分类
        //1级分类
        $fClass=GoodsClass::instance()->info(['name'=>$data['categoryFPreName'],'df'=>0,'cid'=>$cid,'level'=>1]);
        if($fClass){
            $fclass_id=$fClass['id'];
        }else{
            $fclass_id=GoodsClass::instance()->add(['name'=>$data['categoryFPreName'],'df'=>0,'cid'=>$cid,'level'=>1,'cd'=>$this->time,'cb_id'=>0]);
        }
        //2级分类
        $sClass=GoodsClass::instance()->info(['name'=>$data['categoryPreName'],'df'=>0,'cid'=>$cid,'level'=>2]);
        if($sClass){
            $sclass_id=$sClass['id'];
            GoodsClass::instance()->edit(['id'=>$sclass_id],['pid'=>$fclass_id]);
        }else{
            $sclass_id=GoodsClass::instance()->add(['name'=>$data['categoryPreName'],'df'=>0,'cid'=>$cid,'level'=>2,'cd'=>$this->time,'pid'=>$fclass_id,'cb_id'=>0]);
        }
        //3级分类
        $supplyClass=GoodsSupplyClass::instance()->info(['name'=>$data['categoryName'],'cid'=>$cid]);
        $class=GoodsClass::instance()->info(['name'=>$data['categoryName'],'df'=>0,'cid'=>$cid,'level'=>3]);
        if($class){
            $class_id=$class['id'];
            GoodsClass::instance()->edit(['id'=>$class_id],['pid'=>$sclass_id]);
        }else{
            $class_id=GoodsClass::instance()->add(['name'=>$data['categoryName'],'df'=>0,'cid'=>$cid,'level'=>3,'cd'=>$this->time,'pid'=>$sclass_id,'cb_id'=>0]);
        }
        if(empty($supplyClass)){
            $supplyClassData['cid']=$cid;
            $supplyClassData['name']=$data['categoryName'];
            $supplyClassData['supply_id']=is_null($data['categoryId'])?'':$data['categoryId'];
            $supplyClassData['class_id']=$class_id;
            $supplyClassId=GoodsSupplyClass::instance()->add($supplyClassData);
        }else{
            $supplyClassId=$supplyClass['id'];
            if($supplyClass['class_id']>0){
                //如果供应商分类已关联了渠道分类
                $class_id=$supplyClass['class_id'];
            }
        }
        $goodsInfo['class_id']=$class_id;
        $goodsInfo['supply_class_id']=$supplyClassId;
        $goodsInfo['supply_brand_id']=$data['brandID'];

        if(empty($data['brandName'])){
            $data['brandName']='其他';
        }
        $brand=GoodsBrand::instance()->info(['name'=>$data['brandName'],'df'=>0,'cid'=>$cid]);
        if(empty($brand)){
            $in_b['name']=$data['brandName'];
            $in_b['cd']=$this->time;
            $in_b['cid']=$cid;
            $in_b['cb_id']=0;
            $brand['id']=Goodsbrand::instance()->add($in_b);
        }
        $brand_id=$brand['id'];
        $goodsInfo['brand_id']=$brand_id;
        //运费模板
        $template=TransitTemplate::instance()->info(['cid'=>$cid,'status'=>1,'df'=>0]);
        $template_id=empty($template)?0:$template['id'];
        $goodsInfo['template_id']=$template_id;
        //云仓运费模板
        $freight_template=$data['freight_template']??'';
        $goodsInfo['isfree_postfee']=$isFreePostFee=$data['isFreePostFee']??1;
        $express_template_id=0;
        if(!empty($freight_template) && is_array($freight_template) && $isFreePostFee==0){
            $express_template=ExpressTemplate::instance()->info(['template_id'=>$freight_template['template_id']]);
            if($express_template){
                ExpressTemplate::instance()->edit(['id'=>$express_template['id']],['init_weight'=>$freight_template['init_weight'],'init_money'=>$freight_template['init_money'],'increase_weight'=>$freight_template['increase_weight'],'increase_money'=>$freight_template['increase_money']]);
                $express_template_id=$express_template['id'];
            }else{
                $express_template_id=ExpressTemplate::instance()->add(['template_id'=>$freight_template['template_id'],'init_weight'=>$freight_template['init_weight'],'init_money'=>$freight_template['init_money'],'increase_weight'=>$freight_template['increase_weight'],'increase_money'=>$freight_template['increase_money']]);
            }
        }
        $goodsInfo['express_template']=$express_template_id;
        foreach ($sku as $k => $v) {
            $check_sku = Goods::instance()->info(['cid'=>$cid, 'skucode' => $v['skucode']]);
            $buy_limit = $v['limit_buy_count']??0;
            if($buy_limit>0){
                $goodsInfo['buy_limit']=$buy_limit;
                $goodsInfo['limit_type']=2;
            }
            $goodsInfo['df']=$v['status']==0?1:0;
            $goodsInfo['md']=$this->time;
            $goodsInfo['commodity_customer_info']=!empty($v['commodity_customer_info'])?json_encode($v['commodity_customer_info']):'';
            $goodsInfo['commission_level_list']=!empty($v['commission_level_list'])?json_encode($v['commission_level_list']):'';
            $goodsInfo['tax_rate']=$v['tax_rate']??0;
            $goodsInfo['weight']=$v['weight']??0;
            $goodsInfo['tax_free']=$v['has_rate']??0;
            $goodsInfo['barcode']=$v['barcode']??0;
            if ($check_sku) {
                //删除当前商品有的所有批次信息
                GoodsBatch::instance()->del(['goods_id'=>$check_sku['id'],'type'=>0]);
                $spec_list=$v['storeList'][0]['goods_batch_list'][0]['spec_list']??[];
                $spec_list=array_values(array_column($spec_list,null,'spec_num'));
                $spec=array_column($spec_list,'spec_num');
                $has_spec_list=GoodsSpecPrice::instance()->lists(['goods_id'=>$check_sku['id']]);
                $spec_old=[];
                foreach ($has_spec_list as $spec_key => $spec_value){
                    if(!in_array($spec_value['spec_num'],$spec)){
                        GoodsSpecPrice::instance()->del(['id'=>$spec_value['id']]);
                        unset($has_spec_list[$spec_key]);
                    }else{
                        $spec_old[$spec_value['spec_num']]=$spec_value;
                    }
                }
                foreach ($spec_list as $spec_new){
                    $spec_edit=[];
                    if($spec_old && isset($spec_old[$spec_new['spec_num']])){
                        $old=$spec_old[$spec_new['spec_num']];
                        $spec_edit['price_cost']=$spec_new['priceSettlement'];
                        $spec_edit['price_market']=$spec_new['priceMarket'];
                        $spec_edit['price']=$spec_new['price'];
                        $spec_edit['spec_name']=$spec_new['specName'];
                        $spec_edit['price_vip']=empty($spec_new['priceVip'])?$spec_new['price']:$spec_new['priceVip'];
                        GoodsSpecPrice::instance()->edit(['id'=>$old['id']],$spec_edit);
                    }else{
                        $spec_edit['price_cost']=$spec_new['priceSettlement'];
                        $spec_edit['goods_id']=$check_sku['id'];
                        $spec_edit['spec_num']=$spec_new['spec_num'];
                        $spec_edit['spec_name']=$spec_new['specName'];
                        $spec_edit['price_market']=$spec_new['priceMarket'];
                        $spec_edit['price']=$spec_new['price'];
                        $spec_edit['price_vip']=empty($spec_new['priceVip'])?$spec_new['price']:$spec_new['priceVip'];
                        GoodsSpecPrice::instance()->add($spec_edit);
                    }
                }
                if($v['status']==0){
                    $businessGoods=BusinessGoods::instance()->lists(['goods_id'=>$check_sku['id'],'cid'=>$cid,'_fields_'=>'id']);
                    foreach ($businessGoods as $keys=>$values){
                        $businessDeleteItem['id']=$values['id'];
                        $return['channelDelete'][]=$businessDeleteItem;
                    }
                }else{
                    $businessGoods=BusinessGoods::instance()->lists(['goods_id'=>$check_sku['id'],'cid'=>$cid,'_fields_'=>'id,level_id']);
                    $businessInsertItem=[
                        'goodsId'=>$check_sku['id'],
                        'name'=>$goodsInfo['name'],
                        'classifyID'=>$class_id,
                        'brandName'=>$data['brandName'],
                        'isActive'=>$check_sku['status']==1?true:false
                    ];
                    foreach ($businessGoods as $keys=>$values){
                        $businessInsertItem['id']=$values['id'];
                        $businessInsertItem['channelID']=$values['level_id'];
                        $return['channelInsert'][]=$businessInsertItem;
                    }
                }
                $class_name = Goodsclass::instance()->where('id', $check_sku['class_id'])->value('name');
                $storeList = empty($v['storeList']) ? [] : $v['storeList'];
                if(!empty($storeList)){
                    $goodsInfo=$this->chooseBatch(['storeList'=>$storeList,'goods_info'=>$goodsInfo,'goods_id'=>$check_sku['id'],'is_new'=>0,'info'=>$check_sku]);
                }
                $change = [
                    'goods_name' => ['old' => $check_sku['name'], 'now' => $goodsInfo['name']],
                    'goods_class' => ['old' => $class_name, 'now' => $data['categoryName']],
                    'goods_type' => ['old' => $goods_type[$check_sku['is_bonded']], 'now' => $data['goodsTypeName']],
                    'img' => ['old' => $check_sku['img'], 'now' => $goodsInfo['img']],
                    'body' => ['old' => $check_sku['body'], 'now' => $goodsInfo['body']],
                    'price_cost' => ['old' => $check_sku['price_cost'], 'now' => $v['price_cost']],
                    'price_vip' => ['old' => $check_sku['price_vip'], 'now' => $v['price_vip']??0],
                    'price_market' => ['old' => $check_sku['price_market'], 'now' => $v['price_market']],
                    'tax_rate' => ['old' => $check_sku['tax_rate'], 'now' => $v['tax_rate']],
                ];
                $change_log = [
                    'goods_id' => $check_sku['id'],
                    'info' => json_encode($change,JSON_UNESCAPED_UNICODE),
                    'skucode' => $v['skucode'],
                    'barcode' => $v['barcode'],
                    'cd' => $this->time
                ];
                GoodsSyncLog::instance()->insert($change_log);
                $num_storage = Goodsbatch::instance()->where(['goods_id'=>$check_sku['id'],'df'=>0,'type'=>0])->sum('num');
                $goodsInfo['num_storage'] = $num_storage;
                Goods::instance()->where('id', $check_sku['id'])->update($goodsInfo);
                if(count($goods_img)>1){
                    unset($goods_img[0]);
                    GoodsAttach::instance()->where(['goods_id'=>$check_sku['id'],'type'=>1])->delete();
                    foreach ($goods_img as $ki=>$vi){
                        GoodsAttach::instance()->insert(['goods_id'=>$check_sku['id'],'type'=>1,'url'=>$vi,'md'=>$this->time,'cd'=>$this->time]);
                    }
                }
            } else {
                $goodsInfo['is_sync']=1;
                $goodsInfo['cid']=$cid;
                $goodsInfo['skucode']=$v['skucode'];
                $goodsInfo['cd']=$this->time;
                $service=GoodsService::instance()->lists(['cid'=>$cid,'is_default'=>1,'status'=>1,'_fields_'=>'id']);
                if(!empty($service)){
                    $goodsInfo['service_id']=implode(',',array_column($service,'id'));
                }
                $storeList = $v['storeList'];
                $goods_id = Goods::instance()->add($goodsInfo);
                $goods_sql['id']=$goods_id;
                if(!empty($storeList)){
                    $this->chooseBatch(['storeList'=>$storeList,'goods_info'=>$goodsInfo,'goods_id'=>$goods_id,'is_new'=>1]);
                }
                if(count($goods_img)>1){
                    unset($goods_img[0]);
                    foreach ($goods_img as $ki=>$vi){
                        GoodsAttach::instance()->insert(['goods_id'=>$goods_id,'type'=>1,'url'=>$vi,'md'=>time(),'cd'=>time()]);
                    }
                }
            }
            $this->successCount+=1;
        }
        return $return;
    }

    public function chooseBatch($array=[])
    {
        $storeList=$array['storeList'];
        $sql=$array['goods_info'];
        $goods_id=$array['goods_id'];
        $is_new=$array['is_new'];
        foreach ($storeList as $bk=>$bv){
            $num=array_sum(array_column($bv['goods_batch_list'],'num'));
            if($num>0){
                $bv['goods_id']=$goods_id;
                $storage = Storage::instance()->info(['code'=>$bv['store_code']]);
                if(!$storage){
                    $storage = [
                        'code'=>$bv['store_code'],
                        'name'=>$bv['store_name'],
                        'desc'=>$bv['store_name'],
                        'store_type'=>$bv['store_type'],
                        'store_mode'=>$bv['store_mode'],
                        'cd'=>$this->time
                    ];
                    $storage_id = Storage::instance()->add($storage);
                    $storage['id'] = $storage_id;
                }
            }
        }
        $storageChoose=$storeList[0];
        $storage = Storage::instance()->info(['code'=>$storageChoose['store_code']]);
        $batch =[];
        foreach ($storageChoose['goods_batch_list'] as $batchListValue){
            if($batchListValue['num']>0){
                $batch=$batchListValue;
                break;
            }
        }
        if(empty($batch)){
            $batch=$bv['goods_batch_list'][0]??[];
        }
        $storage_num=$batch['num']??0;
        $spec_list=$batch['spec_list']??[];
        $storageChoose['store_isCombineOrders']=$storageChoose['store_isCombineOrders']??null;
        $goods_batch_sql = [
            'cd'=>$this->time,
            'md'=>$this->time,
            'num'=>$storage_num,
            'batch_no'=>empty($batch['batch_no'])?'':$batch['batch_no'],
            'make_date'=>isset($batch['spec_list'][0]['make_date'])?strtotime($batch['spec_list'][0]['make_date']):0,
            'expired_date'=>isset($batch['spec_list'][0]['expired_date'])?strtotime($batch['spec_list'][0]['expired_date']):0,
            'storage_code'=>$storageChoose['store_code'],
            'storage_name'=>$storageChoose['store_name'],
            'supplier_id'=>$storageChoose['store_id'],
            'supplier_name'=>empty($storageChoose['supplier_alias'])?'':$storageChoose['supplier_alias'],
            'store_isCombineOrders'=>$storageChoose['store_isCombineOrders']?1:0,
            'storage_id'=>$storage['id'],
            'goods_id'=>$goods_id,
            'spec_list'=>json_encode($spec_list,JSON_UNESCAPED_UNICODE),
        ];
        $baseSpec=1;
        if(isset($batch['spec_list'][0]['spec_num']) && $batch['spec_list'][0]['spec_num']>1){
            $baseSpec=$batch['spec_list'][0]['spec_num'];
        }
        Goodsbatch::instance()->add($goods_batch_sql);
        $num_storage = Goodsbatch::instance()->where(['goods_id'=>$goods_id,'df'=>0])->sum('num');
        $updateData['num_storage']=$num_storage;
        $updateData['stoid']=$sql['stoid']=$storage['id'];
        $updateData['base_spec']=$sql['base_spec']=$baseSpec;
        $updateData['price_cost']=$sql['price_cost']=$spec_list[0]['priceSettlement']??0;
        $updateData['price_market']=$sql['price_market']=$spec_list[0]['priceMarket']??0;
        $updateData['price']=$sql['price']=$spec_list[0]['price']??0;
        $updateData['price_vip']=$sql['price_vip']=!empty($spec_list[0]['priceVip'])?$spec_list[0]['priceVip']:$updateData['price'];
        if($is_new==0){
            return $sql;
        }else{
            $inArray=[];
            $item['goods_id']=$goods_id;
            $spec_list=array_values(array_column($spec_list,null,'spec_num'));
            foreach ($spec_list as $sp_value){
                $item['spec_num']=$sp_value['spec_num'];
                $item['spec_name']=$sp_value['specName'];
                $item['price']=$sp_value['price'];
                $item['price_vip']=!empty($sp_value['priceVip'])?$sp_value['priceVip']:$sp_value['price'];
                $item['price_cost']=$sp_value['priceSettlement'];
                $item['price_market']=$sp_value['priceMarket'];
                $inArray[]=$item;
            }
            if(!empty($inArray)){
                GoodsSpecPrice::instance()->insertAll($inArray);
            }
            Goods::instance()->edit(['id'=>$goods_id],$updateData);
            return true;
        }
    }

    /**
     * 删除商品
     * @param array $data
     * @param int $cid
     * @return  array
     */
    public function goodsSkuChange( array $message )
    {
        $data = $message['data'];
        $cid  = $message['cid'];
        $channelDelete=[];
        try {
            Db::startTrans();
            $goods=$this->delGoods($data,$cid);
            if(!empty($goods['channelDelete'])){
                $channelDelete=array_merge($channelDelete,$goods['channelDelete']);
            }
            Db::commit();
            if(!empty($channelDelete)){
                (new GoodsElasticSearchMessageService('channel'))->pushNew($channelDelete,'delete');
            }
            return ['code'=>Normal::SUC,'msg'=>'success'];
        } catch (\Exception $e) {
            Db::rollback();
            $msg = $e->getMessage();
            return ['code'=>Normal::FAIL,'msg'=>$msg];
        }
    }

    /**
     * 商品变更
     * @param array $data
     * @param int $cid
     * @return  array
     */
    public function delGoods($data,$cid)
    {
        $sku = $data['skuList'];
        $goods_ids=BusinessGoods::instance()->lists([['skucode','in',$sku],['cid','=',$cid],'_fields_'=>'id']);
        $ids=array_column($goods_ids,'id');
        $return=[];
        foreach ($ids as $v){
            $return['channelDelete'][]=[
                'id'=>$v,
            ];
        }
        Goods::instance()->edit([['skucode','in',$sku],['cid','=',$cid],['df','=',0]],['df'=>1,'md'=>time()]);
        return $return;
    }

    /**
     * 全部下架
     */
    public function goodsBatchDown( array $message )
    {
        $cid = $message['cid'];
//        $goodsIds=BusinessGoods::instance()->lists(['cid'=>$cid,'_fields_'=>'id']);
        $goodsIds=Goods::instance()->alias('g')
            ->field('bg.id')
            ->join('business_goods bg','bg.goods_id=g.id')
            ->where(['g.cid'=>$cid,'g.df'=>0])
            ->select()
            ->toArray();
        if(!empty($goodsIds)){
            (new GoodsElasticSearchMessageService('channel'))->pushNew($goodsIds,'delete');
        }
        Goods::instance()->edit([['is_sync','=',1],['cid','=',$cid],['df','=',0]],['df'=>1,'md'=>time()]);
        return ['code'=>Normal::SUC,'msg'=>'success'];
    }

    /**
     * 分类变更
     */
    public function classChange( array $message )
    {
        $data = $message['data'];
        $cid  = $message['cid'];
        $before=$data['before'];
        $after=$data['after'];
//        if($after['ClassificationLevel']==3 && !empty($after['ClassificationID'])){
//            $supplyClass=GoodsSupplyClass::instance()->info(['name'=>$before['ClassificationName'],'cid'=>$cid]);
//            if($supplyClass){
//                GoodsSupplyClass::instance()->edit(['id'=>$supplyClass['id']],['name'=>$after['ClassificationName'],'supply_id'=>$after['ClassificationID']]);
//            }else{
//                $supplyClassData['cid']=$cid;
//                $supplyClassData['name']=$after['ClassificationName'];
//                $supplyClassData['supply_id']=$after['ClassificationID'];
//                $class=Goodsclass::instance()->info(['name'=>$after['ClassificationName'],'df'=>0,'cid'=>$cid,'level'=>3]);
//                if($class){
//                    $supplyClassData['class_id']=$class['id'];
//                }
//                GoodsSupplyClass::instance()->add($supplyClassData);
//            }
//        }
        $class=Goodsclass::instance()->info(['name'=>$before['ClassificationName'],'df'=>0,'cid'=>$cid,'level'=>$after['ClassificationLevel']]);
        if($class){
            Goodsclass::instance()->edit(['id'=>$class['id']],['name'=>$after['ClassificationName'],'icon'=>$after['ClassificationImage'],'md'=>time()]);
        }
        return ['code'=>Normal::SUC,'msg'=>'success'];
    }

    /**
     * 品牌变更
     */
    public function brandChange( array $message )
    {
        $data = $message['data'];
        $cid  = $message['cid'];
        $before=$data['before'];
        $after=$data['after'];
        $brand=Goodsbrand::instance()->info(['name'=>$before['BrandName'],'cid'=>$cid,'df'=>0]);
        if(empty($brand)){
            $newBrand=Goodsbrand::instance()->info(['name'=>$after['BrandName'],'df'=>0]);
            if(empty($newBrand)){
                $in_b['name']=$after['BrandName'];
                $in_b['pic']=$after['BrandImage'];
                $in_b['cd']=time();
                $in_b['cid']=$cid;
                $in_b['cb_id']=0;
                Goodsbrand::instance()->add($in_b);
            }else{
                Goodsbrand::instance()->edit(['id'=>$newBrand['id']],['pic'=>$after['BrandImage'],'md'=>time()]);
            }
        }else{
            Goodsbrand::instance()->edit(['id'=>$brand['id']],['name'=>$after['BrandName'],'pic'=>$after['BrandImage'],'md'=>time()]);
//            $goods=Goods::instance()->lists(['brand_id'=>$brand['id'],'cid'=>$cid,'df'=>0,'_fields_'=>'id,class_id,name,brand_id,cid,status']);
            $where=[
              'g.brand_id'=>$brand['id'],
              'g.cid'=>$cid,
              'g.df'=>0,
            ];
            $goods=Goods::instance()->alias('g')
                ->field('g.status,g.name,bg.id,bg.level_id,bg.goods_id,g.class_id')
                ->join('business_goods bg','bg.goods_id=g.id')
                ->where($where)
                ->select()
                ->toArray();
            $channel=[];
            foreach ($goods as $v){
                $idxData['id']=$v['id'];
                $idxData['goodsId']=$v['goods_id'];
                $idxData['name']=$v['name'];
                $idxData['classifyID']=$v['class_id'];
                $idxData['channelID']=$v['level_id'];
                $idxData['brandName']=$after['BrandName'];
                $idxData['isActive']=$v['status']==1?true:false;
                $channel[]=$idxData;
            }
            if(!empty($channel)){
                (new GoodsElasticSearchMessageService('channel'))->pushNew($channel,'insert');
            }
        }
        return ['code'=>Normal::SUC,'msg'=>'success'];
    }

    /**
     * 国家变更
     */
    public function countryChange( array $message )
    {
        $data = $message['data'];
        $cid  = $message['cid'];
        $before=$data['before'];
        $after=$data['after'];
        print_r($data);
        Goods::instance()->edit(['origin'=>$before['CountryName'],'cid'=>$cid],['origin'=>$after['CountryName']]);
        $info=Country::instance()->info(['name'=>$before['CountryName'],'cid'=>$cid]);
        $afterInfo=Country::instance()->info(['name'=>$after['CountryName'],'cid'=>$cid]);
        if($info){
            Country::instance()->edit(['id'=>$info['id']],['name'=>$after['CountryName'],'md'=>time(),'icon'=>$after['CountryImage']]);
        }else{
            if($afterInfo){
                Country::instance()->edit(['id'=>$afterInfo['id']],['md'=>time(),'icon'=>$after['CountryImage']]);
            }else{
                $add['name']=$after['CountryName'];
                $add['cd']=time();
                $add['md']=time();
                $add['icon']=$after['CountryImage'];
                $add['code']=$after['CountryCode'];
                $add['cid']=$cid;
                Country::instance()->add($add);
            }

        }
        return ['code'=>Normal::SUC,'msg'=>'success'];
    }

    /**
     * spu变更
     */
    public function spuChange(array $message)
    {
        return ['code'=>Normal::SUC,'msg'=>'success'];
    }
}
